import React, {useState, useRef} from 'react';
import {View, Text, TouchableOpacity} from 'react-native';
import {Button, ListItem} from '@rneui/base';
import Popover, {
  PopoverMode,
  PopoverPlacement,
} from 'react-native-popover-view';
import {round} from 'lodash';
import {getDefaultHeaderHeight} from '@react-navigation/elements';
import {
  useSafeAreaFrame,
  useSafeAreaInsets,
} from 'react-native-safe-area-context';

export default ({
  children,
  width = 100,
  height,
  marginRight = 0,
  marginTop,
  menu = [],
  visible=false,
}) => {
  const [showPopover, setShowPopover] = useState(visible);
  const frame = useSafeAreaFrame();
  const insets = useSafeAreaInsets();
  const headerHeight = getDefaultHeaderHeight(frame, false, insets.top);

  const modalContentWidth = width;
  const pageContentWidth = (frame.width - modalContentWidth) / 2;
  const x = -round((marginRight - pageContentWidth) / pageContentWidth, 2);

  if (marginTop === undefined || marginTop === null) {
    marginTop = headerHeight;
  }
  if(height === undefined || marginTop === null){
    height = menu.length * 40 || 120;
  }
  const modalContentHeight = height;
  const pageContentHeight = (frame.height - frame.y - modalContentHeight) / 2;
  let y = round((marginTop - pageContentHeight) / pageContentHeight, 2);
  return (
    <>
      <TouchableOpacity
        onPress={() => {
          setShowPopover(true);
        }}>
        {children}
      </TouchableOpacity>
      <Popover
        isVisible={showPopover}
        backgroundStyle={{
          opacity: 0.8,
        }}
        popoverStyle={{
          width: modalContentWidth,
          height: modalContentHeight,
          // backgroundColor: '#f9f9f9',
        }}
        popoverShift={{
          x: x,
          y: y,
        }}
        onRequestClose={() => setShowPopover(false)}>
        {menu.map((item, index) => (
          <TouchableOpacity
            key={index}
            onPress={() => {
              item.onPress?.();
              setShowPopover(false);
            }}>
            <ListItem
              containerStyle={{
                height: 39,
                marginBottom: 1,
                padding: 0,
                paddingLeft: 10,
              }}>
              <Text>{item.title}</Text>
            </ListItem>
          </TouchableOpacity>
        ))}
      </Popover>
    </>
  );
};
